'''
自定义方法
'''

from decimal import Decimal
from common.config import *
import json

class Helper(object):
    def __init__(self):
        pass

    # 价格保留两位小数
    @staticmethod
    def decimalParse(data):

        totalPrice = Decimal(str(data)).quantize(Decimal('0.00'))

        return totalPrice

    # 查询数据方法
    @staticmethod
    def selectData(TABLE, MYSQL):
        MYSQL.cursor.execute(SELECT_SQL.format(TABLE=TABLE))
        result = MYSQL.cursor.fetchall()
        return result

    # 合并数据库
    @staticmethod
    def mergeTable(TABLE=None, MYSQL=None, DATA=None):
        STRING = "";
        VALUE = ""
        for k in DATA:
            STRING += '`' + k + '`,'
            VALUE += '"{' + k + '}",'

        per = '(' + STRING.strip(",") + ')'
        val = '(' + VALUE.strip(",") + ')'
        # 原生SQL
        ORIGIN = 'INSERT INTO `' + TABLE + '`' + per + 'VALUES' + val + ''

        INSERT_SQL = ORIGIN.format(**DATA)

        print(INSERT_SQL)

        MYSQL.cursor.execute(INSERT_SQL)
        MYSQL._conn.commit()

    # 格式化产品信息
    @staticmethod
    def formatProductInfo(KEY=None, VALUE=None):
        # 定义空变量
        STRING = ""
        for k, v in zip(KEY, VALUE):
            STRING += '"' + k + '"' + ":" + '"' + v + '"' + ','
        JSON = '{' + STRING.strip(",") + "}"
        return json.loads(JSON)

    # json数据处理
    @staticmethod
    def perfectJson(params):
        data = []
        ss = (params.split("\n"))
        for e in ss:
            if len(e) == 0:
                pass
            else:
                if "" in e:
                    cc = e.strip("        ")
                    data.append(cc)
        data.pop()
        STRING = ""
        for k in data:
            ks = k.split(":")
            NUM = 0
            for v in (ks):
                NUM += 1
                if NUM == 2:
                    STRING += '"' + v + '"' + ","
                else:
                    STRING += '"' + v + '"' + ":"
        perfectJson = "{" + STRING.strip(",") + "}"
        perfectJson = json.loads(perfectJson)
        return perfectJson

    # 启动脚本方法
    @staticmethod
    def runProcess(mysql, name, func):
        while True:
            # 随机领取一条数据
            dt = mysql.randTask(name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)
            func(dt=dt, mysql=mysql)
